<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    body {
        margin: 0;
    }

    #dv {
        width: 100px;
        height: 100px;
        position: absolute;
        background: hotpink;
        cursor: move;
        left: 300px;
        top: 200px;
    }
</style>

<body>
    <div id="dv"></div>
</body>

</html>
<script>
    //获取元素

    //要用到的事件 onmousedown onmosemove onmouseup

    var dv = document.querySelector("#dv")

    dv.onmousedown = function (e) {//鼠标点下去
        // 鼠标点下去的时候 获取鼠标在盒子中坐标
        var ofX = e.offsetX;
        var ofY = e.offsetY;
        //注册移动事件
        //为了防止把元素甩丢,所以我们可以把事件注册给document
        document.onmousemove = function (e) {
            //获取pageX
            dv.style.left = e.pageX - ofX + "px"
            dv.style.top = e.pageY - ofY + "px"
        }
    }

    dv.onmouseup = function(){
        //鼠标弹起的时候 清空move事件
        document.onmousemove = null
    }
</script>